package com.myteam.fugaocrm.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;

import com.myteam.fugaocrm.modle.FgCompany;
import com.myteam.fugaocrm.service.CompanyServiceImpl;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CompanyController {
	@Resource protected CompanyServiceImpl companyServiceImpl;
	
	@RequestMapping("company/all")
	@ResponseBody
	public ModelAndView all(HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<FgCompany> fgCompanyList = companyServiceImpl.all();
		
		ModelAndView view = new ModelAndView();
		view.addObject("fgCompanyList", fgCompanyList);
		view.setViewName("arch_company.jsp");
		return view;
	}
	
	@RequestMapping("company/delete")
	@ResponseBody
	public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer companyId = Integer.parseInt(request.getParameter("companyId").toString());
		
		companyServiceImpl.deleteOne(companyId);
		
		ModelAndView view = new ModelAndView();
		view.setViewName("redirect:/company/all");
		return view;
	}
	
	@RequestMapping("company/insertorupdate")
	@ResponseBody
	public ModelAndView insertOrUpdate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String companyIdStr = request.getParameter("companyId")+"";
		String companyName = request.getParameter("companyName")+"";
		String companyCode = request.getParameter("companyCode")+"";
		
		//校验
		
		
		//插入或更新
		Date date = new Date();
		String staffName = request.getSession().getAttribute("staffName")+"";
		Map<String, Object> params = new HashMap<String, Object>();
		
		if("".equals(companyIdStr)) {
			//insert
			params.put("companyCode", companyCode);
			params.put("companyName", companyName);
			params.put("createdDate", date);
			params.put("createdUser", staffName);
			params.put("modifiedDate", date);
			params.put("modifiedUser", staffName);
			companyServiceImpl.insert(params);
		}else {
			//update
			Integer companyId = Integer.parseInt(companyIdStr);
			params.put("companyId", companyId);
			params.put("companyCode", companyCode);
			params.put("companyName", companyName);
			params.put("modifiedDate", date);
			params.put("modifiedUser", staffName);
			companyServiceImpl.update(params);
		}
		
		ModelAndView view = new ModelAndView();
		view.setViewName("redirect:/company/all");
		return view;
	}
}
